//
//  HMComposePictureView.swift
//  WeiBoXR
//
//  Created by acer on 16/10/1.
//  Copyright © 2016年 acer. All rights reserved.
//

import UIKit

private let collectionViewCellID = "collectionViewCellID"
class HMComposePictureView: UICollectionView {

    //  点击最后一个cell执行的闭包
    var lastCellCallBack: (()->())?

    lazy var images: [UIImage] = [UIImage]()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let layout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: layout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI() {
        backgroundColor = UIColor.blue
        register(HMCollectionViewCell.self, forCellWithReuseIdentifier: collectionViewCellID)
        dataSource = self
        delegate = self
        isHidden = true

    }
    //  添加图片
    func addImage(image: UIImage) -> Void {
        if images.count == 9 {
            return
        }
        isHidden = false
        images.append(image)
        //  重新加载数据
        reloadData()
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        let itemMargin: CGFloat = 5
        //  计算每项的宽度
        let itemWidth = (width - 2 * itemMargin) / 3
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        layout.minimumLineSpacing = itemMargin
        layout.minimumInteritemSpacing = itemMargin
    }
}

extension HMComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if images.count == 0 || images.count == 9 {
            return images.count
        }
        return images.count + 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellID, for: indexPath) as! HMCollectionViewCell
//        cell.backgroundColor = RandomColor()
        if indexPath.item == images.count {
            cell.image = nil
        } else {
            cell.image = images[indexPath.item]
            cell.indexPath = indexPath
            cell.deleteCallBack = {
                self.images.remove(at: indexPath.item)
                
                if self.images.count == 0 {
                    //  隐藏配图
                    self.isHidden = true
                }
                self.reloadData()
            }
        }
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item == images.count {
            lastCellCallBack?()
        }
    }
}

class HMCollectionViewCell : UICollectionViewCell {
    var callBack: ((IndexPath)->())?
    //  执行删除的闭包
    var deleteCallBack: (()->())?
    //  记录当前的indexPath
    var indexPath: IndexPath?
    //  删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(deleteButtonAction), for: .touchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), for: .normal)
        return button
    }()

    private lazy var imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    var image: UIImage? {
        didSet {
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                //  隐藏删除按钮
                deleteButton.isHidden = true

            } else {
                imageView.image = image
                //  显示删除按钮
                deleteButton.isHidden = false

            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setupUI() {
        
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)

        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsets.zero)
        }
        deleteButton.snp_makeConstraints { (make) in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    //  MARK: --    点击事件
    @objc private func deleteButtonAction() {
        
        print("你删除我了")
        //        if let index = indexPath {
        //            callBack?(index)
        //        }
        deleteCallBack?()
    }

}
